//
//  WebViewController.m
//  DemoForWK
//
//  Created by gtj on 2018/9/20.
//  Copyright © 2018年 Synjones. All rights reserved.
//

#import "WebViewController.h"
#import "CookieHelper.h"
#import <WebKit/WebKit.h>

@interface WebViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>
@property (strong, nonatomic) WKWebView *appWkWebView;
@property(nonatomic, copy)NSString *UrlStr;

@property(nonatomic, weak)UILabel *urlLabel;


@property (assign, nonatomic)  bool testLoadOtherUrlDone ;

@end

@implementation WebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    WKPreferences *preferces = [WKPreferences new];
    preferces.javaScriptCanOpenWindowsAutomatically = YES;
    
    
    configuration.preferences = preferces;
    self.appWkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    
    
    self.appWkWebView.scrollView.bounces =  NO;
    [self.view addSubview:self.appWkWebView];
    
    UIButton *copyButton = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth-70, kScreenHeight-600, 50, 50)];
    copyButton.backgroundColor = [UIColor cyanColor];
    [copyButton setTitle:@"复制" forState:UIControlStateNormal];
    [copyButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [copyButton addTarget:self action:@selector(copyAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:copyButton];
    
    UILabel *urlLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, copyButton.y, kScreenWidth-80, 50)];
    urlLabel.font = [UIFont systemFontOfSize:20];
    urlLabel.numberOfLines = 0;
    urlLabel.textColor = [UIColor colorWithHexString:@"333333"];
    self.urlLabel = urlLabel;
    [self.view addSubview:urlLabel];
    
    self.appWkWebView.UIDelegate = self;
    self.appWkWebView.navigationDelegate = self;
    self.appWkWebView.backgroundColor = [UIColor whiteColor];
    
    
    self.appWkWebView.scrollView.alwaysBounceVertical = YES;
    self.appWkWebView.allowsBackForwardNavigationGestures = YES; // 开启侧滑返回历史界面
    
    
    if ([self.strwich isEqualToString:@"10"]) {
        NSString *pathStr = [[NSBundle mainBundle] pathForResource:@"1111.html" ofType:nil];
        NSURL *pathUrl = [NSURL fileURLWithPath:pathStr];
        NSURL *webUrl = [NSURL URLWithString:@"http://219.143.144.137/home/spa"];
        //        [self.appWkWebView loadFileURL:pathUrl allowingReadAccessToURL:pathUrl];
        [self.appWkWebView loadRequest:[NSURLRequest requestWithURL:webUrl]];
    }else if ([self.strwich isEqualToString:@"11"]){
        
        
        self.UrlStr = @"http://219.143.144.137/home/mvcheader";
        AFHTTPRequestSerializer*seriralzer =[AFHTTPRequestSerializer serializer];
        
        [seriralzer setValue:@"byuuid" forHTTPHeaderField:@"by"];
        [seriralzer setValue:@"12" forHTTPHeaderField:@"byuuid"];
        [seriralzer setValue:@"999" forHTTPHeaderField:@"bysessionid"];
        
        NSMutableURLRequest *request=  [seriralzer requestWithMethod:@"GET" URLString:self.UrlStr parameters:@{} error:nil];
        
        
        [self.appWkWebView loadRequest:request];
        
        
        
    }else if ([self.strwich isEqualToString:@"12"]){
        self.UrlStr =
        @"http://219.143.144.137/home/mvccookie";
        //@"http://dev.skyfox.org/cookie.php";
        NSArray *cookies=  [CookieHelper GetNSHTTPCookieStorageJavaScriptArray];
        NSLog(@"%@", cookies);
        
        [CookieHelper addCookieToURL:[NSURL URLWithString:self.UrlStr] key:@"by" value:@"byuuid"];
        
        
        
        
        NSDictionary *cookieDic = @{@"byuuid":@"12",@"bysessionid":@"999",@"by":@"byuuid"};
        NSMutableString*cookieValue=@"".mutableCopy;
        for (NSString *key in cookieDic) {
            NSString *appendString = [NSString stringWithFormat:@"%@=%@;", key, [cookieDic valueForKey:key]];
            [cookieValue appendString:appendString];
        }
        
        
        AFHTTPRequestSerializer*seriralzer =[AFHTTPRequestSerializer serializer];
        
        [seriralzer setValue:cookieValue forHTTPHeaderField:@"cookie"];
        
        
        NSMutableURLRequest *request=  [seriralzer requestWithMethod:@"GET" URLString:self.UrlStr parameters: @{}  error:nil];
        
        [self.appWkWebView loadRequest:request];
        
    }
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.appWkWebView.configuration.userContentController addScriptMessageHandler:self name:@"uploadPhotos"];
    [self.appWkWebView.configuration.userContentController addScriptMessageHandler:self name:@"getToken"];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self.appWkWebView.configuration.userContentController removeScriptMessageHandlerForName:@"uploadPhotos"];
    [self.appWkWebView.configuration.userContentController removeScriptMessageHandlerForName:@"getToken"];
    
    
}

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
    if (!self.testLoadOtherUrlDone){
        self.testLoadOtherUrlDone=YES;
        [self testLoadOtherUrl];
    }
}


#pragma mark - WKScriptMessageHandler代理方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    
    
    
    if([message.name isEqualToString:@"uploadPhotos"]){ //
        NSLog(@"diaooyong");
        NSString *str = [NSString stringWithFormat:@"测试token=%@", self.token];
        NSString* jsCode = [NSString stringWithFormat:@"receiveToken('%@');",str];
        //调用html页面的js方法
        [self.appWkWebView  evaluateJavaScript :jsCode completionHandler:nil];
    }else if ([message.name isEqualToString:@"getToken"]){
        NSLog(@"diaooyong");
        NSString *str = [NSString stringWithFormat:@"token=%@", self.token];
        NSString* jsCode = [NSString stringWithFormat:@"receiveToken('%@');",str];
        //调用html页面的js方法
        [self.appWkWebView  evaluateJavaScript :jsCode completionHandler:nil];
    }else{
        
    }
}
#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}

-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    self.urlLabel.text = navigationAction.request.URL.absoluteString;
    self.UrlStr = navigationAction.request.URL.absoluteString;
    decisionHandler(WKNavigationActionPolicyAllow);
}
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
    
    return nil;
}
- (void)copyAction{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = self.UrlStr;
    [self.appWkWebView makeToast:@"复制成功"];
}


-(void)testLoadOtherUrl {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 改变网页---检查cockie
      //  [self.appWkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://dev.skyfox.org/cookie.php"]]];
        
        //[self.appWkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:   @"http://219.143.144.137/home/mvccookie"]]];
    });
}





@end


